package baiqitun.stupro.api.service.impl;

import baiqitun.stupro.api.model.RoleInfo;
import baiqitun.stupro.api.model.UserInfo;
import baiqitun.stupro.api.service.UserInfoService;
import baiqitun.stupro.common.constant.SysConstant;
import baiqitun.stupro.common.model.TreeModel;
import baiqitun.stupro.security.entity.SysPermission;
import baiqitun.stupro.security.entity.SysRole;
import baiqitun.stupro.security.entity.SysUser;
import baiqitun.stupro.security.model.vo.Ui;
import baiqitun.stupro.security.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 用户登录信息
 * @author kedaji
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Cacheable(cacheNames = {SysConstant.CACHE_PREFIX + "userInfo"})
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    @Override
    public UserInfo getInfo(String username) {
        SysUser user = sysUserService.getEnabledUserByUsername(username);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(user.getUsername()).setName(user.getRealName());

        RoleInfo roleInfo = new RoleInfo();
        List<SysRole> roles = sysUserRoleService.listRoleByUserId(user.getId());
        roleInfo.setRoles(roles);
        List<TreeModel<SysPermission>> treeModels = new LinkedList<>();
        Map<String, Object> conditions = new HashMap<>(1);
        conditions.put("roles", roles);
        roleInfo.setPermissions((sysPermissionService.listRootTree(new SysPermission(), conditions)));
        userInfo.setRole(roleInfo);
        return userInfo;
    }
}
